

const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const server = http.createServer((req, res) => {
    console.log(req.url);
    //设置编码格式
    res.setHeader('Content-Type', 'text/html;charset=utf8')
    if (req.url === '/') {
        let filePath = path.join(__dirname, './views/index.html')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            if (err) {
                throw err
            }
            res.write(fileContent)
            res.end()
        })
    } else if (req.url === '/public/css/index.css') {
        res.setHeader('Content-Type', 'text/css;charset=utf8')
        let filePath = path.join(__dirname, './public/css/index.css')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            if (err) {
                throw err
            }
            res.write(fileContent)
            res.end()
        })
    } else if (req.url === '/public/imgs/error.png') {
        res.setHeader('Content-Type', 'image/png')
        let filePath = path.join(__dirname, './public/imgs/error.png')
        fs.readFile(filePath, (err, fileContent) => {
            if (err) {
                throw err
            }
            res.write(fileContent)
            res.end()
        })

    }
    else {
        res.setHeader('Content-Type', 'text/html;charset=utf8')
        let filePath = path.join(__dirname, './views/404.html')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            if (err) {
                throw err
            }
            res.write(fileContent)
            res.end()
        })
    }
})

server.listen(3001, () => {
    console.log(`serve is running...`);
})